package com.person.android.ui.fragments;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.person.android.dao.FormatType;
import com.person.android.domain.AudioInfo;
import com.person.android.formatts.R;
import com.person.android.jni.AudioTransformJNI;
import com.person.android.jni.Wav2MP3JNI;
import com.person.android.ui.activity.FileListActivity;
import com.person.android.utils.AudioFormatUtils;
import com.person.android.utils.FileHeaderParserUtils;
import com.person.android.utils.FormatTypeUtils;
import com.person.android.utils.LogUtils;
import com.person.android.utils.ToastUtils;
import com.person.android.utils.TransformStatus;
import com.person.android.widgets.RoundProgressBar;
import com.person.android.widgets.TransformProgressDialog;
import com.person.android.widgets.cutom_spinner.AbstractSpinnerAdapter;
import com.person.android.widgets.cutom_spinner.SpinnerPopWindow;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhaokang on 2015/11/29.
 */
public class TransformFragment extends Fragment implements OnClickListener, AbstractSpinnerAdapter.IOnItemSelectListener {

    private View mView;
    private Context mContext;

    private Button mTransBtn;                   //转换按钮
    private EditText mInputFileET;              //源文件输入框
    private TextView mOutputFileTV;             //目标文件输入框

    private String mInputFile;                  //源文件路径
    private String mOutputFile;                 //源目标文件路径

    private Wav2MP3JNI mp3LameJNI;              //wav-->MP3 的JNI
    private RoundProgressBar mRoundProgressBar; //圆形的转换进度条

    private ImageView mInputIv;                 //源文件列表选择框
    private ImageView mOutputIv;                //目标文件列表选择框

    private String mDstName;
    private boolean mInitialFmtFlag = false;                    //初始化目标格式标志位
    private SpinnerPopWindow mFmtPopWindow;                     //格式下拉选择框
    private AbstractSpinnerAdapter mSpinnerAdapter;             //格式下拉适配器
    private int currentFormatType = FormatType.NONE;            //记录当前的转换方式
    private List<String> mDstFormatList = new ArrayList<>();    //目标文件格式
    private TransformProgressDialog mTransformPrgDialog;        //转换的自定义进度条

    @Override
    public void onItemClick(int pos) {
        mOutputFileTV.setText(mDstName + "." + mDstFormatList.get(pos));
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TransformStatus.TRANSFORMING_PROGRESS:
                    updateProgressBar(msg);
                    break;
                case TransformStatus.TRANSFORMING_PROGRESS_OVER:
                    transformSuccessOver();
                    break;
                case TransformStatus.TRANSFORMING_PROGRESS_EXCEPTION:
                    transformException();
                    break;
            }
        }
    };

    private void transformException() {
        if (mTransformPrgDialog != null && mTransformPrgDialog.isShowing()) {
            mTransformPrgDialog.dismiss();
        }
        ToastUtils.showToast(mContext, mContext.getString(R.string.transform_dialog_exception));
    }

    private void transformSuccessOver() {
        if (mTransformPrgDialog != null && mTransformPrgDialog.isShowing()) {
            mTransformPrgDialog.dismiss();
        }
        ToastUtils.showToast(mContext, mContext.getString(R.string.transform_dialog_success));
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        LogUtils.logInfo(LogUtils.FileListActivityFlag, "TransformFragment onCreateView");
        mView = inflater.inflate(R.layout.fragment_transform, container, false);
        mContext = mView.getContext();
        findViews();
        setListeners();
        return mView;
    }

    @Override
    public void onStart() {
        super.onStart();
        LogUtils.logInfo(LogUtils.FileListActivityFlag, "TransformFragment onStart");
    }

    private void setListeners() {
        mFmtPopWindow.setAdapter(mSpinnerAdapter);
        mFmtPopWindow.refreshData(mDstFormatList, 0);
        mInputIv.setOnClickListener(this);
        mOutputIv.setOnClickListener(this);
        mTransBtn.setOnClickListener(this);
        mFmtPopWindow.setItemListener(this);
        mOutputFileTV.setOnClickListener(this);
    }

    void findViews() {
        mFmtPopWindow = new SpinnerPopWindow(mContext);
        mSpinnerAdapter = new AbstractSpinnerAdapter<String>(mContext) {
        };
        mTransBtn = (Button) mView.findViewById(R.id.transformBtn);
        mInputFileET = (EditText) mView.findViewById(R.id.input_file);
        mOutputFileTV = (TextView) mView.findViewById(R.id.output_file);
        mRoundProgressBar = (RoundProgressBar) mView.findViewById(R.id.roundProgressBar2);
        mRoundProgressBar.setProgress(0);
        mInputIv = (ImageView) mView.findViewById(R.id.inputIV);
        mOutputIv = (ImageView) mView.findViewById(R.id.outputIV);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.transformBtn:
                transformAction();
                break;
            case R.id.inputIV:
                gotoSelectFileListActivity();
                break;
            case R.id.outputIV:
            case R.id.output_file:
                if (mInputFile == null || "".equals(mInputFile)) {
                    ToastUtils.showToast(mContext, mContext.getString(R.string.transform_item_input_file_null));
                    return;
                }
                if (mDstFormatList != null && mDstFormatList.size() > 0) {
                    mDstFormatList.clear();
                }
                mDstFormatList = FormatTypeUtils.getSupportAudioFormat(FormatTypeUtils.getExtensionName(mInputFile));
                mFmtPopWindow.refreshData(mDstFormatList, 0);
                if (mInitialFmtFlag && mDstFormatList.size() > 0) {
                    mFmtPopWindow.showAsDropDown(mOutputFileTV);
                }
                mHasChosen = true;
                break;
        }
    }

    private void gotoSelectFileListActivity() {
        startActivityForResult(new Intent(mContext, FileListActivity.class), 1);
    }

    private String mOutFmt;
    private boolean mHasChosen = false;

    private void transformAction() {

        mInputFile = mInputFileET.getText().toString();
        if ("".equals(mInputFile)) {
            ToastUtils.showToast(mContext, getString(R.string.input_file_null));
            return;
        }

        boolean isLawFormat = AudioFormatUtils.isLawForAudioFormat(FormatTypeUtils.getExtensionName(mInputFile));
        if (!isLawFormat) {
            ToastUtils.showToast(mContext, getString(R.string.not_support_format));
            return;
        }

        String inFmt = FormatTypeUtils.getExtensionName(mInputFile);
        if (mHasChosen) {
            mOutFmt = mFmtPopWindow.getSelectedItem();
        } else {
            ToastUtils.showToast(mContext, getString(R.string.transform_select_format));
            return;
        }

        if (!FormatTypeUtils.isSupportAudioFormat(inFmt, mOutFmt)) {
            ToastUtils.showToast(mContext, getString(R.string.not_support_format));
            return;
        }

        String resultFilePath = mInputFile.replace("." + inFmt, "." + mOutFmt);
        if (FormatTypeUtils.getExtensionName(resultFilePath).equals(FormatTypeUtils.getExtensionName(mInputFile))) {
            ToastUtils.showToast(mContext, getString(R.string.format_same));
            return;
        }

        TransformProgressDialog.Builder builder = new TransformProgressDialog.Builder(mContext);
        builder.setTitle(R.string.transform_dialog_title);
        mTransformPrgDialog = builder.create();
        mTransformPrgDialog.show();
        mTransformPrgDialog.getRoundProgressBar().setMax((int) (new File(mInputFile).length()));
        mTransformPrgDialog.getRoundProgressBar().setTextColor(getResources().getColor(R.color.magenta));
        mTransformPrgDialog.getRoundProgressBar().setCricleProgressColor(getResources().getColor(R.color.magenta));

        LogUtils.logInfo(LogUtils.FileListActivityFlag, "mInputFile:=" + mInputFile);
        LogUtils.logInfo(LogUtils.FileListActivityFlag, "resultFilePath:=" + resultFilePath);
        LogUtils.logInfo(LogUtils.FileListActivityFlag, "length:=" + new File(mInputFile).length());

        new TransformTask(mInputFile, resultFilePath).execute();

    }

    private final class TransformTask extends AsyncTask<Void, Void, Boolean> {
        private String inputFile;
        private String outputFile;

        public TransformTask(String inputFile, String outputFile) {
            this.inputFile = inputFile;
            this.outputFile = outputFile;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            try {

                String inFmt = FormatTypeUtils.getExtensionName(inputFile);
                String outFmt = FormatTypeUtils.getExtensionName(outputFile);
                switch (FormatTypeUtils.getFormat(inFmt, outFmt)) {
                    case FormatType.WAV_MP3:
                        mp3LameJNI = new Wav2MP3JNI(mHandler);
                        currentFormatType = FormatType.WAV_MP3;
                        AudioInfo audioInfo = FileHeaderParserUtils.parseWavFile(inputFile);
                        mp3LameJNI.wavConvertmp3(inputFile, outputFile, audioInfo.sampleRate, audioInfo.quality, audioInfo.bitRate, audioInfo.numChannels, audioInfo.mode);
                        break;
                    case FormatType.MP3_WAV:
                        currentFormatType = FormatType.MP3_WAV;
                        AudioTransformJNI audioTransformJNI = new AudioTransformJNI(mHandler);

                        LogUtils.logInfo(LogUtils.FileListActivityFlag, "***&&&&&&&&&&****");

                        LogUtils.logInfo(LogUtils.FileListActivityFlag, "inputFile:=" + inputFile);
                        LogUtils.logInfo(LogUtils.FileListActivityFlag, "outputFile:=" + outputFile);

                        audioTransformJNI.mp3TransformWav(inputFile, outputFile);

                        LogUtils.logInfo(LogUtils.FileListActivityFlag, "***&&&&&&&&&&****");
                        mHasChosen = false;
                        break;
                    case FormatType.WAV_PCM:
                        currentFormatType = FormatType.WAV_PCM;
                        break;
                }
            } catch (Exception e) {
                LogUtils.logInfo(LogUtils.FileListActivityFlag, "progress update exception");
                return false;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            mTransformPrgDialog.dismiss();
            mTransformPrgDialog = null;
        }
    }

    private void updateProgressBar(Message msg) {
        int progress = msg.getData().getInt("progress");
        if (currentFormatType == FormatType.MP3_WAV) {

            LogUtils.logInfo(LogUtils.FileListActivityFlag, "updateProgressBar progress:=" + progress);

            if (progress == -11) {//表示转换结束
                mTransformPrgDialog.getRoundProgressBar().setProgress(mTransformPrgDialog.getRoundProgressBar().getMax());
            } else {
                progress *= 1024 / 8;
                if (progress > 0) {
                    mTransformPrgDialog.getRoundProgressBar().setProgress(progress * 2);
                }
            }
        } else {
            mTransformPrgDialog.getRoundProgressBar().setProgress(progress * 2);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            String path = (String) data.getExtras().get("path");
            ToastUtils.showToast(mContext, path);
            mInputFile = path;
            mInputFileET.setText(path);
            String[] paths = path.split("/");
            String[] name = paths[paths.length - 1].split("\\.");
            mOutputFileTV.setText(name[0]);
            mDstName = name[0];
            if (mDstFormatList != null && mDstFormatList.size() > 0) {
                mDstFormatList.clear();
            }
            mDstFormatList = FormatTypeUtils.getSupportAudioFormat(name[1]);
            mInitialFmtFlag = true;
            mFmtPopWindow.refreshData(mDstFormatList, 0);
        }
    }
}